package com.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.sql.Blob;

import org.apache.log4j.Logger;

public class ByteUtils {
	static Logger logger = Logger.getLogger(ByteUtils.class);


	public static byte[] toBytes(String text) {
		byte[] bytes = new byte[text.length() / 2];
		return bytes;
	}


	public static byte[] InputStreamToByte(InputStream is) throws IOException {

		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		int ch;
		while ((ch = is.read()) != -1) {
			bytestream.write(ch);
		}
		byte byteData[] = bytestream.toByteArray();
		bytestream.close();

		return byteData;
	}

	public static byte[] blobToBytes(Blob blob) {

		BufferedInputStream is = null;

		try {
			is = new BufferedInputStream(blob.getBinaryStream());
			byte[] bytes = new byte[(int) blob.length()];
			int len = bytes.length;
			int offset = 0;
			int read = 0;

			while (offset < len
					&& (read = is.read(bytes, offset, len - offset)) >= 0) {
				offset += read;
			}
			return bytes;
		} catch (Exception e) {
			return null;
		} finally {
			try {
				is.close();
				is = null;
			} catch (IOException e) {
				return null;
			}
		}
	}

	public static String toString(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		for (byte b : bytes) {
			String hex = Integer.toHexString(b & 0XFF);
			if (hex.length() < 2) {
				sb.append("0");
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}



	public static Object unserialize(InputStream in) {

		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(in);
			Object o = ois.readObject();
			return o;
		} catch (Exception e) {
			logger.error("Unserialize object {}", e);
		} finally {
			if (null != ois) {
				try {
					ois.close();
				} catch (IOException e) {
					logger.error(
							"Serialize object close ObjectOutputStream ref {}",
							e);
				}
			}
		}
		return null;
	}

	public static String size(long size) {
		if (size < 1024) {
			return size + "B";
		} else if (size < 1024 * 1024) {
			return size / 1024 + "K";
		} else if (size < 1024 * 1024 * 1024) {
			return size / 1024 / 1024 + "M";
		} else {
			return size / 1024 / 1024 / 1024 + "G";
		}
	}

	public static boolean equals(byte[] data1, byte[] data2) {
		if ((data1 == null && data2 != null)
				|| (data1 != null && data2 == null)) {
			return false;
		}
		if (data1 == null && data2 == null) {
			return true;
		}

		if (data1.length != data2.length) {
			return false;
		}

		for (int i = 0; i < data1.length; i++) {
			if (data1[i] != data2[i]) {
				return false;
			}
		}
		return true;

	}
}
